package com.damacheng009.future.alarm.job;

import java.util.List;

import org.nutz.dao.Dao;
import org.ta4j.core.BaseTimeSeries;
import org.ta4j.core.TimeSeries;
import org.ta4j.core.indicators.SMAIndicator;
import org.ta4j.core.indicators.helpers.ClosePriceIndicator;
import org.ta4j.core.indicators.helpers.CrossIndicator;

import com.damacheng009.future.alarm.domain.TKLine;
import com.damacheng009.future.alarm.toolkit.DaoTool;
import com.damacheng009.future.alarm.toolkit.GlobalConfig;
import com.damacheng009.future.alarm.toolkit.MailTool;
import com.damacheng009.future.alarm.toolkit.MiscTool;

public class PerDayJob {

	public void run() {
		// 每个交易日收盘后，对日线进行一次分析
		// 执行时间应在DayKLines2DBJob之后
		for (String code : GlobalConfig.sinaCodeList) {
			// 初始化K线时间序列
			Dao dao = DaoTool.createDao(code);
			List<TKLine> klines = dao.query(TKLine.class, null);
			
			TimeSeries series = new BaseTimeSeries.SeriesBuilder().withName("oneday_series").build();

			for (TKLine line : klines) {
				// 如果当前K线的结束时间跟上一跟相同则跳过
				if (!series.isEmpty() && MiscTool.changeShanghaiToUTC(line.getDate() + " 00:00:00").isEqual(series.getLastBar().getEndTime())) {
					continue;
				}
				
				series.addBar(MiscTool.changeShanghaiToUTC(line.getDate() + " 00:00:00"), line.getOpen(), 
						line.getHigh(), line.getLow(), line.getClose(), line.getVolume());
			}
			
			ClosePriceIndicator closePriceIndicator = new ClosePriceIndicator(series);
			
			SMAIndicator sma55Indicator = new SMAIndicator(closePriceIndicator, 55);
			
			int endIndex = series.getEndIndex();
			
			// 下穿指标
			CrossIndicator downCrossIndicator = new CrossIndicator(closePriceIndicator, sma55Indicator);
			
			// 上穿指标
			CrossIndicator upCrossIndicator = new CrossIndicator(sma55Indicator, closePriceIndicator);
			
			String msg = code;
			
			if (downCrossIndicator.getValue(endIndex)) {
				msg += " 现价下穿55日均线";
				System.out.println(msg);
				MailTool.send("条件预警", msg);
			} else if (upCrossIndicator.getValue(endIndex)) {
				msg += " 现价上穿55日均线";
				System.out.println(msg);
				MailTool.send("条件预警", msg);
			}
			
		}
		
	}
	
}
